//
//  ViewController.swift
//  SwiftDemo
//
//  Created by championfu on 2024/11/28.
//

import UIKit
import BlocksKit
import SnapKit
import SwifterSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .orange
        let captchaCodeView = YHCaptchaCodeView()
        view.addSubview(captchaCodeView)
        captchaCodeView.snp.makeConstraints { make in
            make.top.equalTo(150)
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(YHCaptchaCodeView.digitWidth)
        }
    }
}

/*
 def gitee(*names)
   names.each do |name|
     pod name, :git => "https://gitee.com/championfu/#{name}.git"
   end
 end
 */
class YHCaptchaCodeView: UIView {
    
    static let digitWidth: CGFloat = {
        (UIScreen.main.bounds.width - 64 - 50) / 6
    }()
    private let textField: UITextField = {
        let tf = UITextField()
        tf.font = .systemFont(ofSize: 18)
        tf.keyboardType = .asciiCapableNumberPad
        return tf
    }()
    private let backgroundView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.isUserInteractionEnabled = false
        return v
    }()
    private let digitLabels: [UILabel] = {
        (0..<6).map { _ in
            let l = UILabel()
            l.textAlignment = .center
            l.font = .systemFont(ofSize: 18)
            l.clipsToBounds = true
            l.layer.borderColor = UIColor.cyan.cgColor
            l.layer.borderWidth = 0.5
            l.layer.cornerRadius = 4
            l.textColor = .black
            l.backgroundColor = .lightGray
            return l
        }
    }()
    
    
    convenience init() {
        self.init(frame: .zero)
        addSubviews([textField, backgroundView] + digitLabels)
        textField.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        for (idx, label) in digitLabels.enumerated() {
            label.snp.makeConstraints { make in
                make.left.equalTo(CGFloat(idx)*(Self.digitWidth+10))
                make.bottom.equalTo(0)
                make.height.equalToSuperview()
                make.width.equalTo(Self.digitWidth)
            }
        }
        textField.bk_shouldChangeCharactersInRangeWithReplacementStringBlock = { [weak self] tf, range, string in
            guard let self else { return false }
            /// 获取在删除和新增状态下的最终结果
            var result = if string.isEmpty {
                ((tf.text ?? "") as NSString).replacingCharacters(in: range, with: "")
            }else {
                ((tf.text ?? "") + string)
            }
            /// 对结果去除非数字字符，并截取前6位
            result = String(result.compactMap({ $0.isNumber ? $0 : nil }).prefix(6))
            tf.text = result
            ///修复复制粘贴情况下，光标不对的问题
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                if let end = tf.position(from: tf.endOfDocument, offset: 0) {
                    tf.selectedTextRange = tf.textRange(from: end, to: end)
                }
            }
            for (i, l) in digitLabels.enumerated() {
                l.text = i <= result.count ? result[safe: i..<i+1] : nil
            }
            return false
        }
    }
}

